package com.example.kbase.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.kbase.R;
import com.example.kbase.adapter.CategoryAdapter;
import com.example.kbase.fragment.subFragment.AddCategoryFragment;
import com.example.kbase.fragment.subFragment.AddMBaseFragment;
import com.example.kbase.fragment.subFragment.MItem1Fragment;
import com.example.kbase.fragment.subFragment.ModifyCategoryFragment;
import com.example.kbase.fragment.subFragment.ModifyMBaseFragment;
import com.example.kbase.model.ArticleInfo;
import com.example.kbase.model.CategoryInfo;
import com.example.kbase.util.Constant;
import com.example.kbase.util.L;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Request;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements AdapterView.OnItemClickListener{
    private View view;
    private ViewPager mViewPaper;
    private List<ImageView> images;
    private List<View> dots;
    private int currentItem;
    //记录上一次点的位置
    private int oldPosition = 0;
    //存放图片的id
    private int[] imageIds = new int[]{
            R.drawable.viewpager01,
            R.drawable.viewpager02,
            R.drawable.viewpager03,
            R.drawable.viewpager01,
            R.drawable.viewpager05,
    };
    //存放图片的标题
    private String[] titles = new String[]{
            "appleBook",
            "lightRead",
            "reading",
            "windowRead",
            "shelfBook"
    };
    private TextView title;
    private ViewPagerAdapter viewAdapter;
    private ScheduledExecutorService scheduledExecutorService;
    private ProgressDialog dialog;
    private List<CategoryInfo.DataBean> list = new ArrayList<>();
    private CategoryAdapter categoryAdapter;
    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, null);
        initView();
        getData();
        return view;
    }

    private void getData(){
        String url = Constant.BaseUrl+"/category/get_category.do";
        OkHttpUtils
                .get()
                .url(url) //TODO  没有传递参数
                .addParams("categoryId","")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        dialog = new ProgressDialog(getActivity());
                        dialog.setTitle("提示");
                        dialog.setMessage("正在加载...");
                        dialog.show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dialog.dismiss();
                        L.e(response);
                        list.clear();
                        Gson gson  = new Gson();
                        //TODO :Expected Object but Array
                        CategoryInfo categoryInfo = gson.fromJson(response ,CategoryInfo.class);
                        if(categoryInfo!=null){
                            list.addAll( categoryInfo.getData());
                            categoryAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }
    private void initView() {
        ListView listView_cate = view.findViewById(R.id.home_list);
        categoryAdapter = new CategoryAdapter(getActivity(),list);
        listView_cate.setAdapter(categoryAdapter);
        //点击listView中的某一项，进入对应项内容的子fragment
        listView_cate.setOnItemClickListener(this);
        listView_cate.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                menu.setHeaderTitle("Select option");
                menu.add(0, 0, 0, "add Category");
                menu.add(0, 1, 0, "modify this");
            }
        });
        mViewPaper =  view.findViewById(R.id.vp);
        //显示的图片
        images = new ArrayList<>();
        for (int i = 0; i < imageIds.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        //显示的小点
        dots = new ArrayList<>();
        dots.add(view.findViewById(R.id.dot_0));
        dots.add(view.findViewById(R.id.dot_1));
        dots.add(view.findViewById(R.id.dot_2));
        dots.add(view.findViewById(R.id.dot_3));
        dots.add(view.findViewById(R.id.dot_4));

        title =  view.findViewById(R.id.title);
        title.setText(titles[0]);

        viewAdapter = new ViewPagerAdapter();
        mViewPaper.setAdapter(viewAdapter);

        mViewPaper.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                title.setText(titles[position]);
                dots.get(position).setBackgroundResource(R.drawable.point_pressed);
                dots.get(oldPosition).setBackgroundResource(R.drawable.point_unpressed);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

//    //从服务器获取类别显示在主页list
//    protected List<Map<String,Object>> getData(){
//        String cate[] = {"Java","JS","Eng","Math","KunFu"};
//        List<Map<String,Object>> data = new ArrayList<>();
//        for(int i = 0;i <5;i++) {
//            Map<String,Object> map = new HashMap<>();
//            map.put("image",R.mipmap.ic_launcher_round);
//            map.put("text",cate[i]);
//            data.add(map);
//
//        }
//        return data;
//    }

    //todo 上下文菜单
    public boolean onContextItemSelected(MenuItem item) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        //info.id得到listView中选择的条目绑定的id,当前上下文的id
        //todo 获取当前item的对象的id --> 不作点击进入下一个界面，接口中没有，暂不做
//        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        String id = String.valueOf(info.id);

        switch (item.getItemId()) {
            case 0:
                transaction.setCustomAnimations(
                        R.animator.fragment_slide_left_enter,
                        R.animator.fragment_slide_left_exit,
                        R.animator.fragment_slide_right_enter,
                        R.animator.fragment_slide_right_exit).
                        replace(R.id.content_layout,new AddCategoryFragment()).
                        addToBackStack(null);
                break;
            case 1:
                //todo modify
                transaction.setCustomAnimations(
                        R.animator.fragment_slide_left_enter,
                        R.animator.fragment_slide_left_exit,
                        R.animator.fragment_slide_right_enter,
                        R.animator.fragment_slide_right_exit).
                        replace(R.id.content_layout,new ModifyCategoryFragment()).
                        addToBackStack(null);// don't goTo it
                break;

        }
        transaction.commit();
        return super.onContextItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //todo 点击类别项进入文章列表
        FragmentManager manager= getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        MItem1Fragment mif = new MItem1Fragment();
//                TextView tv1 = (TextView) view;
//                Bundle bundle = new Bundle();
//                bundle.putCharSequence("1",tv1.getText().toString());
//                mif.setArguments(bundle);

        transaction.setCustomAnimations(
                R.animator.fragment_slide_left_enter,
                R.animator.fragment_slide_left_exit,
                R.animator.fragment_slide_right_exit,
                R.animator.fragment_slide_right_enter).
                replace(R.id.content_layout,mif).
                addToBackStack(null);
        transaction.commit();
    }

    /*定义的适配器*/
    public class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            // TODO Auto-generated method stub
//          super.destroyItem(container, position, object);
//          view.removeView(view.getChildAt(position));
//          view.removeViewAt(position);
            view.removeView(images.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            // TODO Auto-generated method stub
            view.addView(images.get(position));
            return images.get(position);
        }

    }

    /**
     * 利用线程池定时执行动画轮播
     */
    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(
                new ViewPageTask(),
                2,
                2,
                TimeUnit.SECONDS);
    }


    /**
     * 图片轮播任务
     */
    private class ViewPageTask implements Runnable {

        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mViewPaper.setCurrentItem(currentItem);
        }
    };

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }
}
